from PyQt5.QtWidgets import QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
# 鼠标滚轮缩放图片
class ZoomableLabel(QLabel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAlignment(Qt.AlignCenter)
        self._pixmap = None
        self._scale = 1.0

    def setPixmap(self, pm):
        self._pixmap = pm
        # 不重置 self._scale
        if self._pixmap:
            super().setPixmap(self._scaled())

    def _scaled(self):
        if not self._pixmap:
            return QPixmap()
        w = max(1, int(self._pixmap.width() * self._scale))
        h = max(1, int(self._pixmap.height() * self._scale))
        return self._pixmap.scaled(w, h, Qt.KeepAspectRatio, Qt.SmoothTransformation)

    def wheelEvent(self, ev):
        delta = ev.angleDelta().y()
        step = 0.1 if delta > 0 else -0.1
        self._scale = max(0.1, min(8.0, self._scale + step))
        if self._pixmap:
            super().setPixmap(self._scaled())
